# ps3 module

__all__ = [ "appPath" ]

from _ps3 import *

appPath = bootUsrDirPath
if bootAttributes & (CELL_GAME_ATTRIBUTE_DEBUG | CELL_GAME_ATTRIBUTE_APP_HOME):
    # e.g. /app_home/C:\dev\ue3\Binaries\PS3
    pathSeparator = "\\"
    appPathBits = appPath.split(pathSeparator)    # ../..
    appPath = "\\".join(appPathBits[:-2])
    forceUpperCase = False
else:
    # e.g. /dev_hdd0/game/TEST12345/USRDIR
    pathSeparator = "/"
    forceUpperCase = True

## Monkey-patch rename.

if forceUpperCase:
    import os
    oldRename = os.rename

    def newRename(oldPath, newPath):
        if oldPath.startswith(appPath):
            oldPath = appPath + pathSeparator + oldPath[len(appPath)+1:].upper()
        if newPath.startswith(appPath):
            newPath = appPath + pathSeparator + newPath[len(appPath)+1:].upper()
        return oldRename(oldPath, newPath)

    os.rename = newRename


## Monkey-patch file and open.

if forceUpperCase:
    import __builtin__

    oldFile = __builtin__.file
    oldOpen = __builtin__.open

    def newFile(fileName, *args, **kwargs):
        if fileName.startswith(appPath):
            fileName = appPath + pathSeparator + fileName[len(appPath)+1:].upper()
        return oldFile(fileName, *args, **kwargs)

    newFile.__doc__ = oldFile.__doc__

    def newOpen(fileName, *args, **kwargs):
        if fileName.startswith(appPath):
            fileName = appPath + pathSeparator + fileName[len(appPath)+1:].upper()
        return oldOpen(fileName, *args, **kwargs)

    newFile.__doc__ = oldFile.__doc__

    __builtin__.file = newFile
    __builtin__.open = newOpen

## Monkey-patch posixpath.

if forceUpperCase:
    import posixpath
    oldExists = posixpath.exists

    def exists(a):
        if a.startswith(appPath):
            a = appPath + pathSeparator + a[len(appPath)+1:].upper()
        return oldExists(a)

    def join(a, *p):
        """Join two or more pathname components, inserting '/' as needed"""
        path = a
        for b in p:
            if b.startswith('/'):
                path = b.upper()
            elif path == '' or path.endswith(pathSeparator):
                path += b.upper()
            else:
                path += pathSeparator + b.upper()
        return path

    posixpath.exists = exists
    posixpath.join = join
